package com.witsoft.device.controller;

import com.witsoft.device.entity.DeviceStatusTimeLineEntity;
import com.witsoft.device.enums.MachineStatusEnum;
import com.witsoft.device.enums.Status;
import com.witsoft.device.service.DeviceStatusTimeLineService;
import com.witsoft.device.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.Date;
import java.util.List;


@Slf4j
@RestController
@Api(tags = "设备状态时序Controller", description = "设备状态时序")
@RequestMapping("/iot/deviceStatus")
public class DeviceStatusTimeLineController{

    @Autowired
    private DeviceStatusTimeLineService deviceStatusTimeLineService;

    @GetMapping("/sequence")
    @ApiOperation(value = "获取当天设备的状态时序图")
    public Result list(String id) throws IOException{

        try{
            List<DeviceStatusTimeLineEntity> listByDeviceId = deviceStatusTimeLineService.getListByDeviceId(id);
            //fixed（2021.11.10）：处理当日如果设备一直是运行状态的话，没有关机或者待机事件产生，会导致时序图记录中的end_time字段值一直为null，前台渲染时序图出错的问题
            if(listByDeviceId.size() > 0){
                DeviceStatusTimeLineEntity timeLineEntity = listByDeviceId.get(listByDeviceId.size() -1 );
                if(MachineStatusEnum.RUNNING.getCodeStr().equals(timeLineEntity.getStatus())){
                    timeLineEntity.setEndTime(new Date());
                }
            }
            return Result.success(listByDeviceId);
        }catch (Exception e){
            log.error("获取时序状态异常：{}", e.getMessage());
            return Result.error(Status.FAILED_TIMELINE);
        }
    }
}
